// *** LICENSE HEADER ***
// Filename: ./serec.h
// This file is part of Nodewarz 0.1
// Nodewarz is a 3d OpenGL strategy game
// Copyright (C) 2007 CZestmyr
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// *** END LICENSE HEADER ***
#ifndef SEREC_H
#define SEREC_H

//debug (all cout output lines in serec.cpp are debug)
// #include <iostream>
// #include <ctime>
// using std::cout;
// using std::endl;

#include "definitions.h"
#include <vector>
#include <map>
#include <cstring>
#include "peerdata.h"
#include "packetdata.h"
#include <SDL.h>
#include <SDL_net.h>
#include "ipaddresscomparison.h"
#include "helperfunctions.h"
#include "logger.h"

using std::vector;
using std::map;

//Sender-receiver class that implements some transmission control over UDP
class serec{
    public:
        serec(logger* newLogger);
        ~serec();

        //Init the serec on the given UDP port
        bool Init(Uint16 port);
        //Update the serec, sending the unsent packets
        void Update(Sint32 dt);
        //Unbind the socket
        void Deinit();

        //Get the number of unsent messages to the given host
        int GetUnsentMessageNumber(Uint32 host, Uint16 port);
        //Flush all unsent messages to the given host
        void FlushUnsentMessages(Uint32 host, Uint16 port);

        //Send the whole message queue (useful before deinitializing)
        void TryToSendWholeQueue();

        //Send a message to the given host (append it to the message queue)
        void Send(Uint32 host, Uint16 port, const char* message);
        //Receive messages and return number of messages received
        int Receive();
        //Get another of the received messages and copy the message to the provided buffer
        void GetMessage(Uint32& host, Uint16& port, char* message);
    private:
        //Pointer to the logger class
        logger* theLogger;

        //Socket of the serec
        UDPsocket sock;

        //Received packet vector
        vector<packetData> receivedPackets;
        vector<packetData>::iterator receivedPacketsIterator;

        //Map with all peers and their data
        map<IPaddress, peerData> peers;
};

#endif
